package nacos

import (
	"226zy/service/config"
	"encoding/json"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

type Nacoss struct {
	Mysql struct {
		User     string `json:"User"`
		Password string `json:"Password"`
		Host     string `json:"Host"`
		Port     int    `json:"Port"`
		Database string `json:"Database"`
	} `json:"Mysql"`
	Redis struct {
		Host     string `json:"Host"`
		Password string `json:"Password"`
	} `json:"Redis"`
	Grpc struct {
		Host string `json:"Host"`
		Port int    `json:"Port"`
	} `json:"Grpc"`
	Consul struct {
		Name string `json:"Name"`
		Host string `json:"Host"`
		Port int    `json:"Port"`
	} `json:"Consul"`
}

var Config Nacoss

func NewNaCos() {
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "f061ddbb-7879-4fe9-b009-1ca3ea31b496", // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      config.Conf.Nacos.Host,
			ContextPath: "/nacos",
			Port:        8848,
			Scheme:      "http",
		},
	}
	// 创建动态配置客户端
	client, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	if err != nil {
		return
	}
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: config.Conf.Nacos.DataId,
		Group:  config.Conf.Nacos.Group})
	if err != nil {
		return
	}
	err = json.Unmarshal([]byte(content), &Config)
	if err != nil {
		return
	}
}
